import 'package:flutter/material.dart';

// 图片数据列表
final List<Map<String, String>> imgList = List.generate(
  10,
  (index) => {
    "path": "lib/assets/images/common/img_${(index % 4) + 1}.png",
    "id": "$index"
  },
);

class LayoutPage extends StatefulWidget {
  const LayoutPage({super.key});
  @override
  LayoutPageState createState() => LayoutPageState();
}

class LayoutPageState extends State<LayoutPage> {
  int showType = 1; // 控制展示的组件类型
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 1, // 配置 AppBar 的阴影
        title: const Text("Image List"),
      ),
      body: AnimatedSwitcher(
        duration: const Duration(milliseconds: 300),
        child: ColumnLayout(showType: showType), // 根据 showType 切换布局
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            showType = showType == 1 ? 2 : 1; // 切换 showType 的值
          });
        },
        child: const Icon(Icons.swap_horiz), // 按钮图标
      ),
    );
  }
}

// 用于展示图片的布局
class ColumnLayout extends StatefulWidget {
  final int showType; // 控制展示的布局类型
  const ColumnLayout({super.key, required this.showType});

  @override
  State<ColumnLayout> createState() => _ColumnLayoutState();
}

// 布局状态
class _ColumnLayoutState extends State<ColumnLayout> {
  final ScrollController _scrollController = ScrollController();
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=_scrollController.position.maxScrollExtent && !isLoading) {
      // 已经滚动到底部且未在加载状态
      setState(() {
        isLoading = true;
      });
      // 模拟加载更多数据
      Future.delayed(const Duration(seconds: 2), () {
        setState(() {
          imgList.addAll(List.generate(10,(index) => {
              "path": "lib/assets/images/common/img_${(index % 4) + 1}.png",
              "id": "${imgList.length + index}"
            },
          ));
          isLoading = false;
        });
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return widget.showType == 1 ? _buildGridView(context) : _buildListView(_scrollController);
  }

  // 两行滚动布局，横向滚动
  Widget _buildGridView(BuildContext context) {
    // 将 imgList 平均分成两组  提取图片路径并分组
    final int halfLength = (imgList.length / 2).ceil(); // 每组的长度
    final List<List<String>> splitList = [
      imgList.sublist(0, halfLength).map((item) => item["path"]!).toList(), // 第一组提取 path
      imgList.sublist(halfLength).map((item) => item["path"]!).toList(), // 第二组提取 path
    ];
    return SizedBox(
      height: 208,
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start, // 设置内容水平
            children: [
              // 横向滚动区域
              SizedBox(
                height: 208, // 两行图片的总高度
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal, // 横向滚动
                  child: Column(
                    children: splitList.map((group) {
                      return Row(
                        children: group.map((item) {
                          return Padding(
                            padding:const EdgeInsets.fromLTRB(0, 0, 4, 4), // 每张图片间距
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(8.0), // 圆角半径为 8
                              child: RoundedImage(path: item)
                            ),
                          );
                        }).toList(),
                      );
                    }).toList(),
                  ),
                ),
              ),
            ],
          ),
          // 图标部分
          const Positioned(top: 8, right: 8, child: IconOverlay())
        ],
      ),
    );
  }

  // 列表布局
  Widget _buildListView(ScrollController scrollController) {
    return Column(
      children: [
        Expanded(
          child: ListView.builder(
            controller: scrollController,
            itemCount: imgList.length,
            itemBuilder: (context, index) {
              final imgData = imgList[index];
              return ImageLayout(path: imgData["path"] ?? "", id: imgData["id"] ?? "");
            },
          ),
        ),
        if (isLoading) const Padding( padding: EdgeInsets.all(16.0), child: CircularProgressIndicator()),
      ],
    );
  }
}

// 图标覆盖组件
class IconOverlay extends StatelessWidget {
  const IconOverlay({super.key});
  @override
  Widget build(BuildContext context) {
    return Image.asset(
      'lib/assets/images/common/icon.png',
      width: 24,
      height: 24,
      fit: BoxFit.contain,
    );
  }
}

// 单个图片组件（带圆角）
class RoundedImage extends StatelessWidget {
  final String path;
  const RoundedImage({super.key, required this.path});
  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(8.0),
      child: Image.asset(
        path,
        width: 100,
        height: 100,
        fit: BoxFit.cover,
      ),
    );
  }
}

// 单个图片组件 带文字
class ImageLayout extends StatelessWidget {
  final String path;
  final String id;
  const ImageLayout({super.key, required this.path, required this.id});
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          color: Colors.grey.withOpacity(0.2), // 设置背景色
          child: Image.asset(
            path,
            width: 100,
            height: 120,
            fit: BoxFit.cover, // 让图片适应宽高
          ),
        ),
        const SizedBox(height: 8), // 图片和文字之间的间距
        Text("ID: $id",style: const TextStyle(fontSize: 16)),
      ],
    );
  }
}
